// file: handlers/user_profile.go
package handlers

import (
	"encoding/json"
	"net/http"
	"strings"
	"time"

	"zwai-app/middleware"
	"zwai-app/services"
	"zwai-app/util"

	"go.mongodb.org/mongo-driver/bson/primitive"
)

// updateProfileRequest 用于接收前端传来的可选更新字段
type updateProfileRequest struct {
	Username  *string `json:"username,omitempty"`
	Age       *int    `json:"age,omitempty"`
	Gender    *string `json:"gender,omitempty"`
	Birthday  *string `json:"birthday,omitempty"` // ISO8601
	Hobbies   *string `json:"hobbies,omitempty"`
	Address   *string `json:"address,omitempty"`
	Email     *string `json:"email,omitempty"`
	Signature *string `json:"signature,omitempty"`
	AvatarURL *string `json:"avatarUrl,omitempty"`
}

func updateProfileHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != http.MethodPut {
		// 不存在或方法不对就交给后面的 GET 处理
		return
	}

	var req updateProfileRequest
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{
			"code": 1, "msg": "参数解析失败: " + err.Error(),
		})
		return
	}

	if req.Username == nil || strings.TrimSpace(*req.Username) == "" {
		util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{
			"code": 4,
			"msg":  "用户名不能为空",
		})
		return
	}

	userIDhex := middleware.FromContext(r)
	userID, _ := primitive.ObjectIDFromHex(userIDhex)

	// 如果传了生日字符串，解析成 time.Time
	var birthdayTime *time.Time
	if req.Birthday != nil {
		t, err := time.Parse(time.RFC3339, *req.Birthday)
		if err != nil {
			util.JSONResponse(w, http.StatusBadRequest, map[string]interface{}{
				"code": 2, "msg": "生日格式错误，应为 ISO8601",
			})
			return
		}
		birthdayTime = &t
	}

	// 调用服务层更新
	if err := services.UpdateUserProfile(
		r.Context(),
		userID,
		req.Username,
		req.Age,
		req.Gender,
		birthdayTime,
		req.Hobbies,
		req.Address,
		req.Email,
		req.Signature,
		req.AvatarURL,
	); err != nil {
		util.JSONResponse(w, http.StatusInternalServerError, map[string]interface{}{
			"code": 3, "msg": "更新失败: " + err.Error(),
		})
		return
	}

	util.JSONResponse(w, http.StatusOK, map[string]interface{}{
		"code": 0, "msg": "更新成功",
	})
}
